<template>
	<view class="login-wrap">
		<view class="top-wrap">
			<u--image src="/static/login/longinIocn.png" width="200" 
				customStyle="margin:0 auto;"></u--image>
		</view>

		<view class="main-wrap">
			<u--form :model="loginForm" :rules="rules" ref="form" labelWidth="31">
				<u-form-item prop="username" >
					<view class="main-wrap-ipt">
						<u--input v-model="loginForm.username" clearable border="none" placeholder="请输入用户名"
							prefixIcon="account-fill"
							prefixIconStyle="font-size: 44rpx; color: #3c9cff; margin-right: 10rpx;"
							:clearable="true"></u--input>
					</view>
		
				</u-form-item>
				<u-form-item prop="password" >
					<view class="main-wrap-ipt">
						<u--input v-model="loginForm.password" type="password" clearable border="none" placeholder="请输入密码"
							prefixIcon="lock-fill" prefixIconStyle="font-size: 44rpx; color: #3c9cff; margin-right: 10rpx"
							:clearable="true"></u--input>
					</view>
			
				</u-form-item>
				
				<view class="clause">
					<checkbox-group @change="handleClauseCheckbox">
						<label>
							<checkbox :checked="isClause" style="transform:scale(0.6)" />
						</label>
						<text class="check_text">
							<text>已阅读并同意</text>
							<text class="service" @click="handleService">服务协议</text>
							<text>与</text>
							<text class="privacy" @click="handlePrivacy">隐私政策</text>
						</text>
					</checkbox-group>
				</view>
				<view class="main-btn" @click="handleLogin()">登录
				</view>
			</u--form>

		</view>

	</view>
</template>

<script>
	import projectConfig from '@/env.config.js';
	import {
		getProfile
	} from '@/apis/modules/common.js'

	export default {
		data() {
			return {
				token: '',
				codeUrl: '',
				isClause: false,
				loginForm: {
					username: '',
					password: '',
					rememberMe: false,
					code: '',
					uuid: '',
				},
				rules: {
					username: {
						type: 'string',
						min: 2,
						max: 20,
						required: true,
						message: '请输入用户名',
						trigger: ['blur', 'change']
					},
					password: {
						type: 'string',
						required: true,
						min: 5,
						max: 20,
						message: '请输入密码',
						trigger: ['blur', 'change']
					},
					code: {
						type: 'integer',
						required: true,
						message: '请输入验证码',
						trigger: ['blur', 'change']
					}
				},
				isShowPop: false,
			};
		},
		mounted() {
			this.getToken();
			if (this.token != '' && this.token != null) {
				// 跳转主页
				uni.switchTab({
					url: '/pages/tabBar/home/index'
				});
			} else {
				this.getCode();
				this.getAccount();
			}
		},
		methods: {
			handleLogin() {
				this.$refs.form.validate().then(res => {
					if (!this.isClause) {
						uni.showToast({
							icon: 'none',
							title: '请阅读并勾选协议'
						});
						return;
					}
					// 调用登录
					this.$api.common.login(this.loginForm).then(async res => {
						if (res.code == 200) {
							// 存储token和账号
							this.saveToken(res.token);
							this.saveAccount();
							// 获取用户信息
							let profile = await this.getProfile();
							uni.$u.vuex('profile', profile);
							// 跳转主页
							uni.switchTab({
								url: '/pages/tabBar/home/index'
							});
						} else {
							if (res.msg) {
								uni.showToast({
									icon: "none",
									title: res.msg,
									complete: (res) => {
										setTimeout(() => {
											this.getCode();
										}, 1500);
									}
								})
							}
						}
					})
				}).catch(errors => {
					uni.$u.toast('账号信息不能为空');
				});
			},
			// 微信登录
			handleWeChatLogin() {
				let that = this;
				uni.login({
					provider: 'weixin',
					onlyAuthorize: false,
					success: function(loginRes) {
						if (loginRes) {
							console.log('用户授权成功');
							uni.request({
								url: projectConfig.baseUrl + '/wechat/mobileLogin',
								data: {
									//业务服务器通过code + 仅保存在服务器的appsecret参数，向：微信开放平台接口发起网络请求
									code: loginRes.code,
									accessToken: loginRes.authResult.access_token,
									expiresIn: loginRes.authResult.expires_in,
									refreshToken: loginRes.authResult.refresh_token,
									openId: loginRes.authResult.openid,
									unionId: loginRes.authResult.unionid,
								},
								method: 'post',
								success: async res => {
									if (res.data.code == 200) {
										if (res.data.data.token != null) {
											that.saveToken(res.data.data.token);
											that.saveAccount();
											// 获取用户信息
											let profile = await that.getProfile();
											uni.$u.vuex('profile', profile);
											// 跳转主页面
											wx.switchTab({
												url: '/pages/tabBar/home/index'
											})
										} else {
											//跳转绑定页面
											uni.navigateTo({
												url: '/pages/login/bindLogin?bindId=' + res
													.data.data.bindId,
											})
										}
									} else {
										uni.showToast({
											icon: "none",
											mask: true,
											title: res.data.msg,
											duration: 3000,
										})
									}
								},
								fail(err) {
									console.log(err)
								}
							});
						}
					},
					fail(err) {
						console.log(err)
					}
				})
			},
			// 微信一键登录
			handleWeChatOneClickLogin() {
				this.isShowPop = true;
			},
			// 获取验证码
			getCode() {
				this.$api.common.captchaImage().then(res => {
						this.codeUrl = 'data:image/gif;base64,' + res.img;
						this.loginForm.uuid = res.uuid;
						this.loginForm.code = '';
					})
					.catch(err => {
						this.$u.toast(err.msg);
					});
			},
			// 用户注册
			handleRegister() {
				uni.$u.route('/pages/login/register');
			},
			//短信登录
			gotoSmsLogin() {
				uni.$u.route('/pages/login/smsLogin');
			},
			// 获取用户信息
			getProfile() {
				return new Promise((resolve, reject) => {
					getProfile().then(res => {
						resolve(res.data);
					}).catch(err => {
						this.$u.toast(err.msg);
					})
				});
			},
			saveToken(token) {
				// 本地缓存存储token
				uni.setStorageSync('token', token);
				// vuex存储token
				uni.$u.vuex('vuex_token', token);
			},
			getToken() {
				// 本地缓存获取token
				this.token = uni.getStorageSync('token');
				// vuex存储token
				uni.$u.vuex('vuex_token', this.token);
			},
			saveAccount() {
				// 本地缓存存储
				uni.setStorageSync('username', this.loginForm.username);
				uni.setStorageSync('password', this.loginForm.password);
			},
			//微信小程序登录获取手机号
			getPhoneNumber(e) {
				let that = this;
				wx.login({
					success(res) {
						if (e.detail.code && res.code) {
							console.log('用户授权成功');
							//发起网络请求
							wx.request({
								url: projectConfig.baseUrl + '/wechat/miniLogin',
								data: {
									code: res.code,
									phoneCode: e.detail.code,
								},
								method: 'post',
								success: async res => {
									if (res.data.code == 200) {
										// 存储token和账号
										const token = wx.setStorageSync('token', res.data.data.token)
										that.saveToken(res.data.data.token);
										that.saveAccount();
										// 获取用户信息
										let profile = await that.getProfile();
										uni.$u.vuex('profile', profile);
										// 跳转主页
										wx.switchTab({
											url: '/pages/tabBar/home/index'
										});
									} else {
										wx.showToast({
											icon: "none",
											mask: true,
											title: res.data.msg,
											duration: 3000,
										})
									}
								},
							})
						} else {
							console.log('用户拒绝授权');
						}
					}
				})
			},
			getAccount() {
				// 本地缓存获取
				let username = uni.getStorageSync('username');
				let password = uni.getStorageSync('password');
				if (username && username != '') {
					this.loginForm.username = username;
				}
				if (password && password != '') {
					this.loginForm.password = password;
				}
			},
			// 服务协议
			handleService() {
				let title = '服务协议';
				let url = projectConfig.officialWebUrl + 'service-agreement.html';
				uni.navigateTo({
					url: `/pages/common/webview/privacy?title=${title}&url=${url}`
				});
			},
			// 隐私政策
			handlePrivacy() {
				let title = '隐私政策';
				let url = projectConfig.officialWebUrl + 'privacy-policy.html';
				uni.navigateTo({
					url: `/pages/common/webview/privacy?title=${title}&url=${url}`
				});
			},
			// 勾选协议
			handleClauseCheckbox(e) {
				this.isClause = !this.isClause;
			}
		}
	};
</script>

<style lang="scss">
	page {
		height: 100vh;
	}

	.login-wrap {
		height: 100%;
		background-image: url(/static/login/loginBj.png);
		background-size: 100% 100%;
		overflow: hidden;
		
		.top-wrap{
			padding-top: 60rpx;
			
		}
		
		.main-wrap {
			padding: 60rpx;
			
			.main-wrap-ipt{
				width: 100%;
				background-color: white;
				padding: 20rpx ;
				border-radius: 40rpx;
			}
			
			.clause{
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				font-size: 24rpx;
				color: #323233;
				line-height: 40rpx;
				text-align: left;
				font-style: normal;
				text-transform: none;
				margin-top: 100rpx;
				
				.service{
					color: #165DFF;
				}
				
				.privacy{
						color: #165DFF;
				}
				
			
				
			}
			.main-btn{
				margin-top: 20rpx;
				background: #0192DA;
				border-radius: 1998rpx 1998rpx 1998rpx 1998rpx;
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				font-size: 28rpx;
				color: #FFFFFF;
				line-height: 40rpx;
				text-align: center;
				font-style: normal;
				text-transform: none;
				padding: 20rpx 0;
			}
		}
	}
</style>